﻿using Commons.ASPNETCore;
using IdentityService.Domain;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;

namespace IdentityService.Webapi.Controllers.Login
{
    [Route("Identity/[controller]/[action]")]
    [ApiController]
    public class LoginController : ControllerBase
    {

        private readonly IIdRepository repository;
        private readonly IdDomainService idService;

        public LoginController(IdDomainService idservice, IIdRepository repository)
        {
            this.idService = idservice;
            this.repository = repository;
        }


        [HttpGet]
        [Authorize]
        public async Task<Result> GetUserInfo()
        {
            string userId = this.User.FindFirstValue(ClaimTypes.NameIdentifier);
            string role = this.User.FindFirstValue(ClaimTypes.Role);
            var user = await repository.FindByIdAsync(long.Parse(userId));
            if (user == null)//可能用户注销了
            {
                return Result.Fail(CodeType.NO_DATA);
            }
            //出于安全考虑，不要机密信息传递到客户端
            //除非确认没问题，否则尽量不要直接把实体类对象返回给前端
            return Result.Success(new {user.UserName , role });
        }

        [HttpGet]
        [Authorize]
        public Result GetRole()
        {
            string role = this.User.FindFirstValue(ClaimTypes.Role);
            return Result.Success( new {  role });
        }

        [AllowAnonymous]
        [HttpPost]
        public async Task<Result> LoginByUserNameAndPwd(
    LoginByUserNameAndPwdRequest req)
        {
            (bool checkResult,int Errocount, string token) = await idService.LoginByUserNameAndPwdAsync(req.UserName, req.Password);
            if (checkResult) return Result.Success( token!);
            else if (Errocount>5)//尝试登录次数太多
                return Result.Fail(CodeType.NO_DATA);
            else
            {
                return Result.Fail(CodeType.PASSWORD_ERROR);
            }
        }
    }
}
